package com.smh.demo1.a28;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author shiminghui
 * @date 2025/5/3 17:11
 * @description: TODO
 */
@ControllerAdvice
public class HandlerExceptionAdvice {

    @ExceptionHandler
    @ResponseBody
    public Result handle(Exception e) {
        System.out.println("ControllerAdvice: " + e.getMessage());
        return Result.error(e.getMessage());
    }

    static class Result {
        private int code;
        private String msg;
        private Object data;

        public static Result ok() {
            Result result = new Result();
            result.setCode(200);
            result.setMsg("success");
            return result;
        }

        public static Result error(String msg) {
            Result result = new Result();
            result.setCode(500);
            result.setMsg(msg);
            return result;
        }

        @Override
        public String toString() {
            return "Result{" +
                    "code=" + code +
                    ", msg='" + msg + '\'' +
                    ", data=" + data +
                    '}';
        }

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }

        public Object getData() {
            return data;
        }

        public void setData(Object data) {
            this.data = data;
        }
    }

}
